package site.user.action;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import modules.recruit.entity.ApplyBase;
import modules.recruit.entity.ApplyConfirm;
import modules.recruit.entity.ApplyManager;
import modules.recruit.service.RegionImageService;
import modules.system.entity.Contact;
import modules.system.entity.User;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import site.user.form.ApplyBaseFormSite;

import com.guinea.core.orm.Page;
import com.guinea.core.orm.PropertyFilter;
import com.guinea.core.service.EntityService;
import com.guinea.core.utils.CommonUtils;
import com.guinea.core.utils.ServletUtils;
import com.guinea.core.web.StrutsEntityAction;

import ex.recruit.service.ApplyBaseServiceEx;
import ex.recruit.service.ApplyManagerServiceEx;
import ex.system.service.AttachServiceEx;
import ex.system.service.UserServiceEx;

public class ApplyBaseActionSite extends StrutsEntityAction {

	private ApplyBaseServiceEx applyBaseServiceEx;

	ApplyManagerServiceEx applyManagerServiceEx;

	private RegionImageService regionImageService;

	AttachServiceEx attachServiceEx;

	UserServiceEx userServiceEx;

	public EntityService getEntityService() {
		return applyBaseServiceEx;
	}

	public ApplyBaseServiceEx getApplyBaseServiceEx() {
		return applyBaseServiceEx;
	}

	public void setApplyBaseServiceEx(ApplyBaseServiceEx applyBaseServiceEx) {
		this.applyBaseServiceEx = applyBaseServiceEx;
	}

	public ApplyManagerServiceEx getApplyManagerServiceEx() {
		return applyManagerServiceEx;
	}

	public void setApplyManagerServiceEx(
			ApplyManagerServiceEx applyManagerServiceEx) {
		this.applyManagerServiceEx = applyManagerServiceEx;
	}

	public AttachServiceEx getAttachServiceEx() {
		return attachServiceEx;
	}

	public void setAttachServiceEx(AttachServiceEx attachServiceEx) {
		this.attachServiceEx = attachServiceEx;
	}

	public RegionImageService getRegionImageService() {
		return regionImageService;
	}

	public void setRegionImageService(RegionImageService regionImageService) {
		this.regionImageService = regionImageService;
	}

	public UserServiceEx getUserServiceEx() {
		return userServiceEx;
	}

	public void setUserServiceEx(UserServiceEx userServiceEx) {
		this.userServiceEx = userServiceEx;
	}

	public ActionForward declare(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		return mapping.findForward("declare");
	}

	public ActionForward downloadValidator(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		initFirst(form, request);
		if (!validateEntity())
			return handleEntityMissing(mapping, form, request, response);
		ApplyBase applyBase = (ApplyBase) entity;
		if (!"1".equals(applyBase.getIsSubmitted())) {
			valid = false;
			saveDirectlyError(request, "该申请尚未提交，不能下载。");
			return mapping.findForward(LIST);
		}
		return null;
	}

	public ActionForward download(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		ServletContext servletContext = request.getSession()
				.getServletContext();
		List provinces = (List) servletContext.getAttribute("provinces");
		List cities = (List) servletContext.getAttribute("cities");
		List districts = (List) servletContext.getAttribute("districts");
		String result = getApplyBaseServiceEx().getWord(id, provinces, cities,
				districts);
		renderWord(response, "斯柯达特许销售商入网申请书.doc", result);
		return null;
	}

	/**
	 * 列出所有对象的Action函数.
	 */
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		// 从request中获取含属性前缀名的参数,构造去除前缀名后的参数Map.
		Map filterParamMap = ServletUtils.getParametersStartingWith(request,
				FILTER_PREFIX + "_");
		List filters = PropertyFilter.buildFromParaMap(filterParamMap);
		Page page = PropertyFilter.buildPageFromHttpRequest(request,
				REQUEST_PAGE);

		page = getApplyBaseServiceEx().getApplyProcess(page, filters, false,
				true);

		request.setAttribute(REQUEST_PAGE, page);
		request.setAttribute(FILTER_MAP, filterParamMap);
		return mapping.findForward(LIST);
	}

	/**
	 * 显示修改对象Form的Action函数.
	 */
	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		if (!isCreateOperation) {
			ApplyBase applyBase = (ApplyBase) entity;
			
			if(!CommonUtils.couldApplyBeModified(applyBase)){
				valid = false;
				saveDirectlyError(request, "该申请已提交，不能再修改。");
				return mapping.findForward(LIST);
			}
		}
		// 创建操作，带出基本信息
		if (isCreateOperation) {
			Long userId = CommonUtils.getCurrentUserId();
			User user = getUserServiceEx().getUser(userId);
			if (user != null) {
				bindForm(form, user.getContact());
				ApplyBaseFormSite applyBaseFormSite = (ApplyBaseFormSite) form;
				applyBaseFormSite.setId(null);
			}
		} else {
			bindForm(form, entity);
		}

		if (!isCreateOperation) {
			ApplyBaseFormSite applyBaseFormSite = (ApplyBaseFormSite) form;
			ApplyManager applyManager = getApplyManagerServiceEx()
					.getManagerByBasePosition(id, "1");
			if (applyManager != null) {
				applyBaseFormSite.setOwner(applyManager.getOwner());
				applyBaseFormSite.setCellphone(applyManager.getCellphone());
				applyBaseFormSite.setEmail(applyManager.getEmail());
			}
		}

		return handleEdit(mapping, form, request, response);
	}

	/**
	 * 保存前的验证.
	 */
	public ActionForward saveValidator(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		if (isCancelled(request)) {
			valid = false;
			return mapping.findForward(LIST);
		}

		if (!validateToken(request))
			return handleToken(mapping, form, request, response);

		initFirst(form, request);
		return null;
	}

	/**
	 * 保存对象的Action函数.
	 */
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		doInitEntity(request, form);

		doSaveEntity(request, form);

		saveApplyManager(form);

		// save contact
		Long userId = CommonUtils.getCurrentUserId();
		User user = getUserServiceEx().getUser(userId);
		if (user != null) {
			Contact contact = user.getContact();
			Long contactId = null;
			if (contact == null) {
				contact = new Contact();
				contact.setUser(user);
			} else {
				contactId = contact.getId();
			}
			bindEntity(form, contact);
			contact.setId(contactId);
			getEntityService().saveOrUpdate(contact);
		}

		String direction = request.getParameter("direction");
		if (direction != null && direction.equals("next")) {
			return new ActionForward(
					"/site/user/applyEquity.do?method=edit&applyBaseId="
							+ id.toString(), true);
		} else {
			saveMessage(request, "entity.saved");
			return handleEdit(mapping, form, request, response);
		}
	}

	/**
	 * 查看业务对象（不能修改）的Action函数.
	 */
	public ActionForward view(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		request.setAttribute("apply", entity);
		ApplyBase applyBase = (ApplyBase) entity;
		if (applyBase != null && applyBase.getSubmitDate() != null) {
			request.setAttribute("submitDateStr",
					CommonUtils.formatDate(applyBase.getSubmitDate()));
		}
		// List imagesOfRegion1 = new ArrayList();
		// List imagesOfRegion2 = new ArrayList();
		// if(applyBase != null){
		// for (Iterator iter = applyBase.getRegion().iterator();
		// iter.hasNext();) {
		// Region region = (Region) iter.next();
		// if("1".equals(region.getStatus()) && "1".equals(region.getSerial())){
		// for (Iterator iterator = region.getImages().iterator(); iterator
		// .hasNext();) {
		// RegionImage regionImage = (RegionImage) iterator.next();
		// if("1".equals(regionImage.getStatus()) && regionImage.getAttachId()
		// != null){
		// Attach attach =
		// getAttachServiceEx().getAttach(regionImage.getAttachId());
		// if (attach != null) {
		// String attachPath = StringUtils.defaultString(attach.getWebPath());
		// imagesOfRegion1.add(attachPath);
		// }
		// }
		// }
		// }
		// }
		//
		// }

		return mapping.findForward(VIEW);
	}

	private void saveApplyManager(ActionForm form) {
		ApplyManager applyManager = getApplyManagerServiceEx()
				.getManagerByBasePosition(id, "1");
		if (applyManager == null) {
			applyManager = new ApplyManager();
			applyManager.setPosition("1");
			applyManager.setBase((ApplyBase) entity);
		}
		ApplyBaseFormSite applyBaseFormSite = (ApplyBaseFormSite) form;
		applyManager.setOwner(applyBaseFormSite.getOwner());
		applyManager.setCellphone(applyBaseFormSite.getCellphone());
		applyManager.setEmail(applyBaseFormSite.getEmail());

		getApplyManagerServiceEx().saveOrUpdate(applyManager);
	}

}
